package com.faf.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.faf.bean.Comment;
import com.faf.dao.CommentDao;

public class CommentDaoImpl extends BaseDaoImpl implements CommentDao {
	public CommentDaoImpl() {

	}

	public CommentDaoImpl(Connection con) {
		super(con);
	}
	@Override
	public ArrayList<Comment> getCommentByStoreID(int storeId, int currentPage, int pageTotal) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "select commentId,userId,ordersNumber,commentTime,commentContext,commentScore from comment where storeId = ? limit ?,?";
		executeQuery(sql, storeId, (currentPage - 1) * pageTotal, pageTotal);
		Comment comment = null;
		ArrayList<Comment> comments = new ArrayList<Comment>();
		while (rs.next()) {
			comment = new Comment();
			comment.setCommentId(Integer.parseInt(rs.getString("commentId")));
			comment.setStoreId(storeId);
			comment.setUserId(Integer.parseInt(rs.getString("userId")));
			comment.setOrdersNumber(rs.getString("ordersNumber"));
			comment.setCommentScore((rs.getDouble("commentScore")));
			comment.setCommentTime((rs.getString("commentTime")));
			comment.setCommentContext((rs.getString("commentContext")));
			comments.add(comment);
		}
		return comments;
	}

	@Override
	public int getAllCommentRecordBystoreId(int storeId) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "select count(1) from comment where storeId = ?";
		executeQuery(sql, storeId);
		int result = 0;
		if (rs != null) {
			if (rs.next()) {
				result = rs.getInt(1);
				System.out.println(result);
			}
		}
		return result;
	}

	@Override
	public boolean newComment(int userId, String ordersNumber, String commentContext, double commentScore, int storeId) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "insert into comment (userId, ordersNumber, commentTime, commentContext, commentScore, storeId) values (?,?,?,?,?,?)";
		this.executeUpdate(sql, userId, ordersNumber, 
				(new SimpleDateFormat("yyyy-MM-dd")).format(new Date(System.currentTimeMillis())),
				commentContext, commentScore, storeId);
		return true;
	}

	@Override
	public Comment getCommentByOrderNumber(String orderNumber) throws SQLException {
		// TODO Auto-generated method stub
		String sql = "select * from comment where ordersNumber = ?";
		executeQuery(sql, orderNumber);
		Comment comment = null;
		while (rs.next()) {
			comment = new Comment();
			comment.setCommentId(Integer.parseInt(rs.getString("commentId")));
			comment.setStoreId(rs.getInt("storeId"));
			comment.setUserId(Integer.parseInt(rs.getString("userId")));
			comment.setOrdersNumber(rs.getString("ordersNumber"));
			comment.setCommentScore((rs.getDouble("commentScore")));
			comment.setCommentTime((rs.getString("commentTime")));
			comment.setCommentContext((rs.getString("commentContext")));
		}
		return comment;
	}
}
